from docx import Document as dcm
import Levenshtein
from spire.doc import Document, FileFormat
from bs4 import BeautifulSoup


def compare_two_texts(text1, text2):
    distance = Levenshtein.distance(text1, text2)
    return (len(text1) + len(text2) - distance) / (2 * max(len(text1), len(text2)))


def doc2html(doc_path):
    document = Document()
    document.LoadFromFile(doc_path)
    doc_path = doc_path.split('.')[0]
    h_path = doc_path + '.html'
    document.SaveToFile(h_path, FileFormat.Html)
    document.Close()


def read_html_file(html_path, file_code):
    try:
        with open(html_path, 'r', encoding=file_code) as f:
            html_content = f.read()
    except FileNotFoundError:
        print('File Not Found')
    except OSError as e:
        print(repr(e))

    # 使用bs4解析html
    soup = BeautifulSoup(html_content, 'html.parser')

    return soup


def extract_content(docx_path):
    doc = dcm(docx_path)
    contents = []

    for section in doc.sections:
        contents.append(f"Section: {section.start_type} {section.start.value}")

    for i, paragraph in enumerate(doc.paragraphs):
        contents.append(f"Paragraph {i + 1}: {paragraph.text}")

    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                print(cell.text, end=' ')
            print()

    return contents


def main_func(file_dict):
    f_path_1 = file_dict['filePathOriginal']
    f_path_2 = file_dict['filePathNew']

    # 转化成html格式
    doc2html(f_path_1)
    doc2html(f_path_2)
    contents = Document(file_path)

    # word处理



if __name__ == "__main__":
    text_1 = "脉冲电子围栏是传统的普通围墙与报警系统的完美结合，在具有普通围墙的阻挡作用的基础上，增加报警功能，误报率几乎为0，同时又具有威慑入侵者的作用，因此，脉冲电子围栏系统弥补了传统周界防护报警系统的弱点，具有物理屏障、主动反击、延迟入侵、准确报警、安全防护等特性。"
    text_2 = "脉冲电子围栏是传统的普通围墙与报警系统的完美结合，在具有普通围墙的阻挡作用的基础上，增加报警功能，误报率几乎为0，同时又具有威慑入侵者的作用，因此，脉冲电子围栏系统弥补了传统周界防护报警系统的弱点，具有物理屏障、主动反击、延迟入侵、准确报警、安全防护等特性。"
    similarity = compare_two_texts(text_1, text_2)
    print(similarity)
    file_path = r"C:\Users\hx\PycharmProjects\comparative-analysis-fastapi\docs\电子围栏系统方案(new).docx"
    result = extract_content(file_path)
    print(result)
    pass
